package com.lemon.smartsafety.ui.activity.address;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.AdapterView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.entity.event.address.AddressRefreshEvent;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.UrlInfo;
import com.lemon.smartsafety.http.service.BaseHttpServices;
import com.lemon.smartsafety.result.address.SearchBookMode;
import com.lemon.smartsafetynew.ui.activity.base.BaseActivity;
import com.lemon.smartsafetynew.ui.activity.base.LemonPermissionListener;
import com.lemon.smartsafety.ui.adapter.address.SearchBookAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.SystemUtil;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.view.ViewSearch;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.lemon.smartsafety.view.list.MyListView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

public class SearchBookActivity extends BaseActivity {

    @Bind(R.id.viewSearch)
    ViewSearch viewSearch;
    @Bind(R.id.listView)
    MyListView listView;
    @Bind(R.id.multiStateView)
    MultiStateView mMultiStateView;

    private SearchBookAdapter searchBookAdapter;
    private SearchBookMode searchBookMode;
    private List<SearchBookMode.ResultEntity> resultEntityList;


    @Override
    protected void getBundleArgs() {
     /*   XGPushClickedResult click = XGPushManager.onActivityStarted(this);
        Log.d("TPush", "onResumeXGPushClickedResult:" + click);
        if (click != null) { // 判断是否来自信鸽的打开方式
            Toast.makeText(this, "SearchBookActivity  通知被点击:" + click.toString(),
                    Toast.LENGTH_SHORT).show();
        }*/
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_search_book;
    }

    @Override
    protected void initViews() {
        viewSearch.setSearchBack(new ViewSearch.CallBackInterface() {
            @Override
            public void callBackFunction(View v) {
                search();
            }
        });

        //mMultiStateView.setEmptyTip("通讯录查询搜索");
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        resultEntityList = new ArrayList<>();
        searchBookAdapter = new SearchBookAdapter(this, resultEntityList);
        listView.setAdapter(searchBookAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                final String strPhone = resultEntityList.get(position).getMobile();
                getConfirmDialog("是否拨打电话：" + strPhone, new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            doDialPhone(strPhone);
                        }
                    }
                }).show();

            }
        });


        mMultiStateView.setEmptyTip("通讯录查询搜索");
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
    }


    @Subscribe
    public void onEventMainThread(final AddressRefreshEvent event) {

    }


    private void doDialPhone(final String phone) {
        checkPermission(getString(R.string.permission_call), new LemonPermissionListener() {
            @Override
            public void onPermissionGranted(int requestCode) {
                Intent phoneIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
                if (ActivityCompat.checkSelfPermission(SearchBookActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                SearchBookActivity.this.startActivity(phoneIntent);
            }

            @Override
            public void onPermissionDenied(int requestCode, ArrayList<String> deniedPermissions) {
                mHUDUtil.showErrorTip(getString(R.string.permission_denied_action));
            }
        }, Manifest.permission.CALL_PHONE);
    }



    private void search(){

        if(CommonUtil.strIsEmpty(viewSearch.getEdtContent())){
            mHUDUtil.showErrorTip("搜索内容不能为空");
        }else{
            httpSearch();
            SystemUtil.HideKeyboard(this);
        }

    }


    private void httpSearch(){

        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("op","search_user_list");
        params.put("keywords",viewSearch.getEdtContent());

        BaseHttpServices baseHttpServices=new BaseHttpServices(this);

        HttpOkBase.httpBasePost(params, baseHttpServices.mSharedPreferencesServer.getRequestUrl(UrlInfo.ADDRESS_BOOK_LIST), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                if (httpClient) {
                    try {
                        searchBookMode=  new Gson().fromJson(result, SearchBookMode.class);
                        if (!CommonUtil.objIsEmpty(searchBookMode)) {
                            if (!searchBookMode.isIsError()) {
                                if(CommonUtil.listIsEmpty(searchBookMode.getResult())){

                                    mMultiStateView.setEmptyTip("没有找到相关信息");
                                    mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                                    mHUDUtil.showErrorTip("相关信息记录为空");
                                    return;
                                }

                                mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                                mHUDUtil.hidden();
                                resultEntityList.clear();
                                resultEntityList.addAll(searchBookMode.getResult());
                                searchBookAdapter.notifyDataSetChanged();
                            } else {
                                LoggerHelper.error(getClass(),result);
                            }
                        }
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }





}
